package cn.vcjf.washcar.common.util.weixin;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 郑自航
 * @Auther: zhengzihang
 * @Date: 2018/7/12 11:12
 * @Description:微信官方公众号 支付
 */

public abstract class AbstractWxPayAuth{

	private Logger logger = LoggerFactory.getLogger(AbstractWxPayAuth.class);

	//"http://vcjf.s1.natapp.cc/";//
	public static String BASE_URL="http://m.vc-group.cn/";

	/**
	 * 下单url
	 * @return
	 */
	protected abstract String getUnifiedOrderUrl();
	/**
	 * 当前servlet的url,用来授权重定向
	 * @return
	 */
	protected abstract String getThisServletUrl();

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String queryString = request.getQueryString();
		logger.debug("微信公众号请求参数:{}",queryString);
		//检查参数
		try {
			doCheckRequestParams(request);

			String openId = WxPayAuthApi.getCode(request, response, WxPayAuthApi.APP_ID, WxPayAuthApi.APP_SECRET
					, BASE_URL + getThisServletUrl() + "?" + queryString
			);
			if ("".equals(openId)) {
				response.getWriter().print("获取openId失败");
			}
			//已经获取到openID
			if (openId != null) {

				this.doSuccess( openId, request,  response);
			}
		} catch (Exception e) {
			logger.error("微信公众号请求参数:{}",queryString);
			logger.error("微信公众号请求异常:{}",e);
		}
		return;
	}
	protected abstract void doSuccess(String openId,HttpServletRequest request, HttpServletResponse response) throws IOException;

	protected abstract void doCheckRequestParams(HttpServletRequest request);

	private void setHttpServletContent(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=utf-8");
	}
}
